import { useEffect } from 'react';
import { observable } from 'mobx';
import browser from 'webextension-polyfill';
import PlaybackState from '@/popup/store/PlaybackState';
import UpgradeProject from '@/popup/IO/migrate'; // 版本升级
import ProjectStore from '@/popup/store/ProjectStore';
import UiState from '@/popup/store/UiState';
import ModalState from '@/popup/store/ModalState';
import Logger from '@/popup/store/Logs';

import { loadProject, saveProject, loadJSProject } from '@/popup/IO/filesystem';

const project = observable(new ProjectStore(''));

UiState.setProject(project);
project.setModified(false);

export default function App() {
    // 开始录制
    const startRecord = async () => {
        chrome.tabs.query(
            {
                currentWindow: false,
                active: true,
            },
            (tabs) => {
                console.log(tabs, 'tabs');
                // 给当前tab发送消息，开始录制
                chrome.tabs.sendMessage(tabs[0].id, { attachRecorder: true }, (message) => {
                    if (chrome.runtime.lastError) {
                        console.error('Error sending message:', chrome.runtime.lastError);
                    }
                    console.log(message, 'message');
                });
            },
        );
    };

    // 添加消息监听
    useEffect(() => {
        const onMessage = (message, sender, sendResponse) => {
            try {
                console.log(message, sender, sendResponse, 'popup 收到消息');
            } catch (error) {
                console.error('Error processing message:', error);
            }
        };
        browser.runtime.onMessage.addListener(onMessage);
        return () => {
            browser.runtime.onMessage.removeListener(onMessage);
        };
    }, []);

    useEffect(() => {
        const contents = {
            id: 'ab2153ea-3582-4ca0-9835-0a1b92994716',
            version: '2.0',
            name: 'a',
            url: 'https://www.baidu.com',
            tests: [
                {
                    id: '4d0f4aa4-c78a-46ae-bdb6-7eb5082e8efd',
                    name: 'aaa',
                    commands: [
                        {
                            id: '67cc61b1-33d2-4eb3-85e8-ceedbdaada91',
                            comment: '',
                            command: 'open',
                            target: '/',
                            targets: [],
                            value: '',
                        },
                        {
                            id: 'e9d07a32-91fd-4553-bde4-e51c303445f9',
                            comment: '',
                            command: 'setWindowSize',
                            target: '1722x928',
                            targets: [],
                            value: '',
                        },
                        {
                            id: '09a39a99-dbdd-42de-8022-cf48ac544b94',
                            comment: '',
                            command: 'click',
                            target: 'css=.hotsearch-item:nth-child(1) .title-content-title',
                            targets: [
                                ['css=.hotsearch-item:nth-child(1) .title-content-title', 'css:finder'],
                                ["xpath=//ul[@id='hotsearch-content-wrapper']/li/a/span[2]", 'xpath:idRelative'],
                                ['xpath=//a/span[2]', 'xpath:position'],
                                ["xpath=//span[contains(.,'“一国两制”谱新篇')]", 'xpath:innerText'],
                            ],
                            value: '',
                            opensWindow: true,
                            windowHandleName: 'win3853',
                            windowTimeout: 2000,
                        },
                        {
                            id: '4207927c-2656-4e95-b889-58f97e475d01',
                            comment: '',
                            command: 'storeWindowHandle',
                            target: 'root',
                            targets: [],
                            value: '',
                        },
                        {
                            id: 'd73f5002-2859-4abf-8de4-de47156c78e9',
                            comment: '',
                            command: 'selectWindow',
                            target: 'handle=${win3853}',
                            targets: [],
                            value: '',
                        },
                        {
                            id: '42558f69-d3f8-4ac0-b883-32a8aa716519',
                            comment: '',
                            command: 'click',
                            target: 'css=span > span > em',
                            targets: [
                                ['css=span > span > em', 'css:finder'],
                                [
                                    "xpath=//div[@id='1']/div/div/div/div/div/div/div/div[2]/div/h3/a/div/div/p/span/span/em",
                                    'xpath:idRelative',
                                ],
                                ['xpath=//em', 'xpath:position'],
                                ["xpath=//em[contains(.,'“一国两制”谱新篇')]", 'xpath:innerText'],
                            ],
                            value: '',
                            opensWindow: true,
                            windowHandleName: 'win77',
                            windowTimeout: 2000,
                        },
                        {
                            id: '3810c353-92cc-4af5-99c9-1ef61df73bca',
                            comment: '',
                            command: 'selectWindow',
                            target: 'handle=${win77}',
                            targets: [],
                            value: '',
                        },
                        {
                            id: 'd00e897f-a0fc-44d4-bb8f-d88cb1790444',
                            comment: '',
                            command: 'close',
                            target: '',
                            targets: [],
                            value: '',
                        },
                        {
                            id: '40a563a0-0f11-4afb-9071-876fb194efb2',
                            comment: '',
                            command: 'selectWindow',
                            target: 'handle=${win3853}',
                            targets: [],
                            value: '',
                        },
                        {
                            id: '33af984d-3ace-4718-9993-f518fe73cbfa',
                            comment: '',
                            command: 'close',
                            target: '',
                            targets: [],
                            value: '',
                        },
                        {
                            id: '5afce717-4a3a-4162-a394-938881763fba',
                            comment: '',
                            command: 'selectWindow',
                            target: 'handle=${undefined}',
                            targets: [],
                            value: '',
                        },
                        {
                            id: '552301c3-0671-4268-8d76-96dba5511427',
                            comment: '',
                            command: 'selectWindow',
                            target: 'handle=${root}',
                            targets: [],
                            value: '',
                        },
                        {
                            id: '904eaa73-4106-4d9f-bfba-46aa1f095042',
                            comment: '',
                            command: 'close',
                            target: '',
                            targets: [],
                            value: '',
                        },
                        {
                            id: 'a9e2ba2b-fd88-40c5-bc4e-8ad962e482e8',
                            comment: '',
                            command: 'selectWindow',
                            target: 'handle=${undefined}',
                            targets: [],
                            value: '',
                        },
                    ],
                },
            ],
            suites: [
                {
                    id: 'e9bae5ce-2039-413e-9617-4b0b6ff4c2fc',
                    name: 'Default Suite',
                    persistSession: false,
                    parallel: false,
                    timeout: 300,
                    tests: ['4d0f4aa4-c78a-46ae-bdb6-7eb5082e8efd'],
                },
            ],
            urls: ['https://www.baidu.com/'],
            plugins: [],
        };
        loadJSProject(project, UpgradeProject(contents));
        console.log(project, UiState, 'project');
    }, []);

    return (
        <main>
            <button onClick={startRecord}>开始录制</button>
            <button onClick={PlaybackState.playTestOrResume}>运行</button>
        </main>
    );
}
